package lc20240616;

import lc20240526.ListNode;

/**
  * @description 合并k个有序链表
  * @author 不知名帅哥
  * @date 2024/6/16 23:38
  * @version 1.0
*/
public class MergeKSortedList {
    public static void main(String[] args) {

    }
    //分治合并。当然也可以利用顺序合并，一次跟ans合并。不断使用mergeTwoLists()方法。也不失为一种好方法。虽然效率低。
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        return merge(lists, 0, lists.length - 1);
    }

    private ListNode merge(ListNode[] lists, int left, int right) {
        if (left == right) return lists[left];
        if (left < right) {
            int mid = left + (right - left) / 2;
            ListNode l1 = merge(lists, left, mid);
            ListNode l2 = merge(lists, mid + 1, right);
            return mergeTwoLists(l1, l2);
        }
        return null;
    }

    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}
